/*
{
	"id": "xxx",
	"password": "xxx"
}

callback (isOk, errMsg)
*/
function verifyUser(db, data, callback) {
	var collection = db.get("user");
	collection.findOne({
		"id": data.id
	}, function(err, doc) {
		if (err) {
			console.log("verifyUser err");
			callback(false, err);
		} else if (!doc) {
			console.log("not register: id=" + data.id);
			callback(false, "not register yet");
		} else if (doc.password !== data.password) {
			console.log("wrong password: id=" + data.id);
			callback(false, "wrong password");
		} else {
			callback(true);
		}
	});
}

function verifyAppkey(db, data, callback) {
	var collection = db.get("appKey");
	collection.findOne({
		"appKey": data.appKey
	}, function(err, doc) {
		if (err) {
			console.log("verifyAppkey err");
			callback(false, err);
		} else if (!doc) {
			console.log("invalid appKey =" + data.appKey);
			callback(false, "invalid appKey");
		} else {
			callback(true);
		}
	});
}

/**
 * insert to db, check if exist same deviceUuid
 */
function insertDevice(db, deviceInfo, callback) {
	var collection = db.get("device");

	collection.findOne({
		deviceUuid: deviceInfo.deviceUuid
	}, function(err, rec) {
		if (err) {
			console.log('findOne err ' + err);
			callback(false, err);
		} else if (rec) {
			console.log('device already in db, will not insert twice');
			callback(true, "device already exists");
		} else {
			console.log('insert device into db');
			collection.insert(deviceInfo, function(err, doc) {
				if (err) {
					callback(false, err);
				} else {
					callback(true);
				}
			});
		}
	})
}

function bindDeviceUser(db, info, callback) {
	var collection = db.get('device');
	var filter = {
		deviceUuid: info.deviceUuid
	};
	var updateOpt = {
		$set: {
			userId: info.user.id
		}
	};

	collection.update(filter, updateOpt, function(err, size, status) {
		if (err) {
			console.log('findOne err ' + err);
			callback(false, err);
		} else {
			callback(true);
		}
	});
}

module.exports = {
	verifyUser: verifyUser,
	verifyAppkey: verifyAppkey,
	insertDevice: insertDevice,
	bindDeviceUser:bindDeviceUser
}